package de.tum.in.eist.im.client.Login;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;

import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.RootPanel;

import de.tum.in.eist.im.client.Chat.ChatPanel;
import de.tum.in.eist.im.client.Chat.ChatUI;
import de.tum.in.eist.im.client.Login.LoginService;
import de.tum.in.eist.im.client.Login.LoginServiceAsync;
import de.tum.in.eist.im.shared.User.User;

public class LoginHandler implements ClickHandler, KeyUpHandler {
	
	private LoginPanel loginPanel;

	// create a remote service proxy to talk to the server-side Login service.
	private final LoginServiceAsync loginService = GWT.create(LoginService.class);
	
	/**
	 * constructor for the LoginHandler
	 * @param loginPanel the loginPanel calling this method
	 */
	public LoginHandler(LoginPanel loginPanel) {
		this.loginPanel = loginPanel;
	}
	
	/**
	 * method called if the user clicks a key inside a widget referenced to this method
	 * @param event event which is sent
	 */
	@Override
	public void onKeyUp(KeyUpEvent event) {
		if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
			this.login();
		}
	}

	/**
	 * method called if the user press a button referenced to this method
	 * @param event event which is sent
	 */
	@Override
	public void onClick(ClickEvent event) {
		this.login();
	}
	
	/**
	 * method which checks if the user exist and finally log the user in
	 */
	private void login() {
		// reset the error label
		loginPanel.setErrorLabel("");
		
		// check if all fields are not empty
		if (loginPanel.getUsername().isEmpty() || loginPanel.getPassword().isEmpty()) {
			loginPanel.setErrorLabel("Please fill in all fields!");
		} else {
			
			/* TODO: Encrypt password before call! But beware! Localhost it seems works online not!
			 * 		 Error seems to be that SHAConverter is not really translated to js!
			String encryptedPassword = null;
			try {
				SHAConverter shaConverter = new SHAConverter();
				encryptedPassword = shaConverter.SHA1(loginPanel.getPassword());   
			} catch(Exception e) {}
			*/
			// create user object
			final User user = new User(loginPanel.getUsername(), loginPanel.getPassword());
			
			// asynchronous call to the server
			loginService.loginToServer(
				user,
				new AsyncCallback<Boolean>() {
					public void onFailure(Throwable caught) {
						loginPanel.setErrorLabel(caught.getMessage());
					}
					
					public void onSuccess(Boolean result) {
						if (result) {
							ChatUI chatUI = new ChatUI(user);
							RootPanel.get().clear();
							RootPanel.get().add(chatUI);
							chatUI.requestChatTab("General Group");
						} else {
							loginPanel.setErrorLabel("Please check your input!");
						}
					}
				});
		}
	}
}
